/**------------------------------------------------------------
 *
 * Copyright © 2015 rubbervalley. All rights reserved.
 *
 * @Title: PlatStoreController.java
 * @Package: com.rubbervalley.uyo.actions
 * @Description: 公司/店铺
 * @author: zhoulei
 * @date: 上午10:35:28
 * @version: V1.0
 * 
 * Update History:
 * 
 ------------------------------------------------------------*/
package com.rubbervalley.uyo.actions.administrator;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rubbervalley.common.PagedList;
import com.rubbervalley.common.Pager;
import com.rubbervalley.common.Query;
import com.rubbervalley.common.datatable.ResponseTable;
import com.rubbervalley.common.datatable.TableParam;
import com.rubbervalley.framework.core.common.MessageUtil;
import com.rubbervalley.framework.core.common.ObjectMessages;
import com.rubbervalley.framework.system.business.UserService;
import com.rubbervalley.framework.system.domain.User;
import com.rubbervalley.platform.business.PlatAreaService;
import com.rubbervalley.platform.business.PlatStoreContactService;
import com.rubbervalley.platform.business.PlatStoreService;
import com.rubbervalley.platform.business.PlatStoreUploadfileService;
import com.rubbervalley.platform.business.PlatUploadfileService;
import com.rubbervalley.platform.domain.PlatArea;
import com.rubbervalley.platform.domain.PlatStore;
import com.rubbervalley.platform.domain.PlatStoreContact;
import com.rubbervalley.platform.domain.PlatStoreUploadfile;
import com.rubbervalley.platform.domain.PlatUploadfile;

@Controller
@RequestMapping(value = "/uyo")
public class PlatStoreController {
	@Autowired
	private PlatStoreService platStoreService;
	@Autowired
	private PlatAreaService platAreaService;
	@Autowired
	private PlatStoreUploadfileService platStoreUploadfileService;
	@Autowired
	private PlatUploadfileService platUploadfileService;
	@Autowired
	private PlatStoreContactService platStoreContactService;
	@Autowired
	private MessageUtil messageUtil;
	@Autowired
    private UserService userService;

	private static final Logger logger = LoggerFactory
			.getLogger(PlatStoreController.class);

	@RequestMapping(value = "/platStores")
	String platStores(Map<String, Object> model,PlatStore elem, BindingResult result)
	{
		logger.debug("PlatStoreController");
		model.put("elem", elem);
		return "/uyo/administrator/platStore/platStores.ftl";
	}
	/***
	 * 企业条件查询
	 * 
	 * @param model
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/platStore/ajaxlist1",method=RequestMethod.POST)
	String list(Map<String, Object> model
		,@RequestParam(value="page", required=false, defaultValue="1") int page
		,PlatStore elem, BindingResult result) throws ParseException
	{		
		Query query=new Query();	
		Pager pager=new Pager();
		pager.setPage(page);
		query.setPager(pager);
		Map<String, Object> params = query.getParams();

		params.put("elem", elem);

		PagedList datas=platStoreService.queryByParas(query);

		model.put("datas", datas.getList());
		model.put("elem", elem);
		model.put("pager", pager);
		return "/uyo/administrator/platStore/ajaxList.ftl";
	}

	/***
	 * 企业详情
	 * 
	 */
	@RequestMapping(value = "/platStore/{id}", method = RequestMethod.GET)
	public String detail(Map<String, Object> model,
			@PathVariable("id") Integer id)
	{
		PlatStore bean = platStoreService.select(id);
		model.put("bean", bean);
		
		PlatStoreUploadfile storeFile=new PlatStoreUploadfile();
		storeFile.setStoreId(bean.getId());
		//取出企业相关图片
		List<PlatUploadfile> images= platUploadfileService.selectFileByStoreFile(storeFile,PlatUploadfile.IMAGE_TAG);
		model.put("images", images);
		//取出企业相关文件
		List<PlatUploadfile> files= platUploadfileService.selectFileByStoreFile(storeFile,PlatUploadfile.FILE_TAG);
		model.put("files", files);
		
		//若企业地区id不为空，则逐级取出同等级的全部地区
        if(bean.getAreaId()!=null && bean.getAreaId()!=0){	
        	PlatArea area1=platAreaService.select(bean.getAreaId());
			model.put("thisDistinct", area1);	
			
			PlatArea area2=platAreaService.select(area1.getUppid());
			model.put("thisCity", area2);

			
			PlatArea area3=platAreaService.select(area2.getUppid());
			model.put("thisRegion", area3);
			
			PlatArea area4=platAreaService.select(area3.getUppid());
			model.put("thisCountry", area4);

        }
		return "/uyo/administrator/platStore/detail.ftl";
	}

	public void validate(PlatStore platStore, Errors errors)
	{
		Integer id = platStore.getId();
		PlatStore sp2 = platStoreService.selectStore(platStore);
		// 更新如果有用户、类别、公司名称均相同，则排除
		if( sp2!=null && id!=null   && !(sp2.getId().equals(id))){
			errors.reject("uyo.codeexit.error");
		}
		else if( sp2!=null  && id==null ){ // 增加如果存在已有code，排除
			errors.reject("uyo.codeexit.error");
		}
	}

	/***
	 * 企业添加页面
	 * 
	 */
	@RequestMapping(value = "/platStore/add", method = RequestMethod.GET)
	public String add(Map<String, Object> model)
	{
		PlatArea area = new PlatArea();
		area.setLevelno(PlatArea.LEVEL_COUNTRY);
		List<PlatArea> areas = platAreaService.selectAreaByArea(area);
		model.put("areas", areas);
		return "/uyo/administrator/platStore/add.ftl";
	}

	/***
	 * 提交添加信息
	 * 
	 */
	@RequestMapping(value = "/platStore/add", method = RequestMethod.POST)
	@ResponseBody
	public ObjectMessages add(Map<String, Object> model
			,@RequestParam(value="fileId" , required=false) Integer[] fileId
			,@RequestParam(value="imageId" , required=false) Integer[] imageId
			,@RequestParam(value="contentimageUrl" , required=false) String[] contentimageUrl
			,@RequestParam(value="contactType" , required=false) Integer contactType
			,@RequestParam(value="contactStatus" , required=false) Integer contactStatus
			,@RequestParam(value="contactName" , required=false) String contactName
			,PlatStoreContact contact, PlatStore platStore,BindingResult result)
	{
		// TODO:修改代码
		validate(platStore, result); // 数据校验
		if (result.hasErrors()) {
			// TODO:校验失败
			return messageUtil.messages("common.add.error");
		} else {
			Subject currentUser = SecurityUtils.getSubject();
			if(currentUser.getPrincipal()!=null){
				String loginName=(String) currentUser.getPrincipal().toString();
				User loginUser = userService.findByLoginName(loginName);
				platStore.setOwnerId(loginUser.getId());
			}

			this.platStoreService.insert(platStore);
			
			// 保存文章-附件对应关系
			if(fileId != null && fileId.length>0){
				for(int i=0; i<fileId.length; i++){
					PlatStoreUploadfile elem= new PlatStoreUploadfile();
					elem.setStoreId(platStore.getId());
					elem.setFileId(fileId[i]);
					elem.setTag(PlatUploadfile.FILE_TAG);
					//设置来源
					this.platStoreUploadfileService.insert(elem);
			    }
			}

			// 保存文章-单独上传的图片对应关系
			if(imageId != null && imageId.length>0){
				for(int i=0; i<imageId.length; i++){
					PlatStoreUploadfile elem= new PlatStoreUploadfile();
					elem.setStoreId(platStore.getId());
					elem.setFileId(imageId[i]);
					elem.setTag(PlatUploadfile.IMAGE_TAG);
					//设置来源
					this.platStoreUploadfileService.insert(elem);
			    }
			}
			
			// 保存文章-logo图片对应关系
			setLogoFile(platStore);

			// 保存你联系人信息
			contact.setName(contactName);
			contact.setType(contactType);
			contact.setStatus(contactStatus);
			contact.setStoreId(platStore.getId());
			platStoreContactService.insert(contact);

			return messageUtil.messages("common.add.success");
		}

	}

	/***
	 * 企业信息编辑页
	 * 
	 */
	@RequestMapping(value = "/platStore/{id}/update", method = RequestMethod.GET)
	public String update(Map<String, Object> model,
			@PathVariable("id") Integer id)
	{
		PlatStore bean = platStoreService.select(id);
		model.put("bean", bean);
		
		PlatStoreUploadfile storeFile=new PlatStoreUploadfile();
		storeFile.setStoreId(bean.getId());
		//取出企业相关图片
		List<PlatUploadfile> images= platUploadfileService.selectFileByStoreFile(storeFile,PlatUploadfile.IMAGE_TAG);
		model.put("images", images);
		//取出企业相关文件
		List<PlatUploadfile> files= platUploadfileService.selectFileByStoreFile(storeFile,PlatUploadfile.FILE_TAG);
		model.put("files", files);
		
		PlatArea area = new PlatArea();
		
		//若企业地区id不为空，则逐级取出同等级的全部地区
        if(bean.getAreaId()!=null && bean.getAreaId()!=0){	
        	PlatArea area1=platAreaService.select(bean.getAreaId());
			List<PlatArea> thisDistincts= platAreaService.selectAreaByParentid(area1.getUppid());
			model.put("thisDistincts", thisDistincts);	
			model.put("thisCity", area1.getUppid());
			
			PlatArea area2=platAreaService.select(thisDistincts.get(0).getUppid());
			List<PlatArea> thisCities= platAreaService.selectAreaByParentid(area2.getUppid());
			model.put("thisCities", thisCities);
			model.put("thisRegion", area2.getUppid());
			
			PlatArea area3=platAreaService.select(thisCities.get(0).getUppid());
			List<PlatArea> thisRegions= platAreaService.selectAreaByParentid(area3.getUppid());
			model.put("thisRegions", thisRegions);
			model.put("thisCountry", area3.getUppid());
			
			PlatArea area4=platAreaService.select(thisRegions.get(0).getUppid());
			List<PlatArea> areas = platAreaService.selectAreaByParentid(area4.getUppid());
			model.put("areas", areas);
        }
        else{
        	area.setLevelno(PlatArea.LEVEL_COUNTRY);
    		List<PlatArea> areas = platAreaService.selectAreaByArea(area);
    		model.put("areas", areas);
        }

		return "/uyo/administrator/platStore/update.ftl";
	}

	/***
	 * 提交编辑信息
	 * 
	 */
	@RequestMapping(value = "/platStore/{id}/update", method = RequestMethod.POST)
	@ResponseBody
	public ObjectMessages update(Map<String, Object> model
			,@RequestParam(value="fileId" , required=false) Integer[] fileId
			,@RequestParam(value="imageId" , required=false) Integer[] imageId
			,@RequestParam(value="contentimageUrl" , required=false) String[] contentimageUrl
			,@RequestParam(value="contactType" , required=false) Integer contactType
			,@RequestParam(value="contactName" , required=false) String contactName
			,@RequestParam(value="contactId" , required=false) Integer contactId
			,PlatStoreContact contact,PlatStore platStore, BindingResult result)
	{
		// TODO:修改代码
		validate(platStore, result); // 数据校验
		if (result.hasErrors()) {
			// TODO:校验失败
			return messageUtil.messages("common.update.error");
		} else {			
			platStoreUploadfileService.deleteByStore(platStore);
			
			this.platStoreService.update(platStore);
			// 保存文章-附件对应关系
			if(fileId != null && fileId.length>0){
				for(int i=0; i<fileId.length; i++){
					PlatStoreUploadfile elem= new PlatStoreUploadfile();
					elem.setStoreId(platStore.getId());
					elem.setFileId(fileId[i]);
					elem.setTag(PlatUploadfile.FILE_TAG);
					//设置来源
					this.platStoreUploadfileService.insert(elem);
			    }
			}

			// 保存文章-单独上传的图片对应关系
			if(imageId != null && imageId.length>0){
				for(int i=0; i<imageId.length; i++){
					PlatStoreUploadfile elem= new PlatStoreUploadfile();
					elem.setStoreId(platStore.getId());
					elem.setFileId(imageId[i]);
					elem.setTag(PlatUploadfile.IMAGE_TAG);
					//设置来源
					this.platStoreUploadfileService.insert(elem);
			    }
			}
			// 保存文章-logo图片对应关系
			setLogoFile(platStore);
			
			// 保存你联系人信息			
			contact.setName(contactName);
			contact.setType(contactType);
			contact.setStoreId(platStore.getId());
			if(contactId!=null && contactId!=0){
				contact.setId(contactId);
				platStoreContactService.update(contact);
			}
			else{
				contact.setId(null);
				platStoreContactService.insert(contact);
			}
		    return messageUtil.messages("common.update.success");
		}
	}

	/***
	 * 企业删除
	 * 
	 */
	@RequestMapping(value = "/platStore/{id}/delete")
	@ResponseBody
	public ObjectMessages delete(Map<String, Object> model,
			@PathVariable("id") String id)
	{
		String bi[] = id.split(",");		
		for(int i=0; i<bi.length; i++){
			this.platStoreService.delete(Integer.parseInt(bi[i]));			
	    }		
		return messageUtil.messages("common.delete.success");

	}
	
	/** 
	 * 保存文章-logo图片对应关系
	 * @param platStore
	 */
	void setLogoFile(PlatStore platStore){
		if(platStore.getLogoId() != null ){			
			PlatStoreUploadfile elem= new PlatStoreUploadfile();
			elem.setStoreId(platStore.getId());
			elem.setFileId(platStore.getLogoId());
			elem.setTag(PlatUploadfile.LOGO_TAG);
			//设置来源
			this.platStoreUploadfileService.insert(elem);
		}
	}
	/**
	 * json方式
	 * @param model
	 * @param dqquery
	 * @return
	 */
	@RequestMapping(value="/platStore/ajaxlist/json",produces="application/json")
	@ResponseTable(type="datatable")
	public PagedList queryPlatStores(Map<String, Object> model,@TableParam  Query query)
	{
		
		PagedList pagedlist = this.platStoreService.queryByParaWhere(query);
		return pagedlist;
	}
	/**
	 * footable方式
	 * @param model
	 * @param dqquery
	 * @return
	 */
	@RequestMapping(value="/platStore/ajaxlist")
	public String queryPlatStores(Map<String, Object> model)
	{
		Query query=new Query();
		PagedList pagedlist = this.platStoreService.queryByParaWhere(query);
		model.put("list", pagedlist.getList());
	return "/uyo/administrator/platStore/ajaxList.ftl";
	}
}